﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace g2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Regex reg = new Regex(@"^[0-9]{6}(?<year>[0-9]{4})(?<month>[0-9]{2})(?<day>[0-9]{2})[0-9]{3}[0-9a-zA-Z]$");
            Console.WriteLine("请输入身份证号:");
            string s = Console.ReadLine();
            Match match = reg.Match(s);
            if (match.Success)
            {
                //校验日期
                int year = Convert.ToInt32(match.Result("${year}"));
                int month = Convert.ToInt32(match.Result("${month}"));
                int day = Convert.ToInt32(match.Result("${day}"));
                if (!isLeagal(year, month, day))
                {
                    Console.WriteLine("身份证日期不合法");
                    return;
                }
                //校验最后一位
                int sum = 0;
                int[] array1= new int[17] {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
                int[] array2 = new int[11] {1,0,-1,9,8,7,6,5,4,3,2 };
                for (int i = 0; i < 17; i++)
                {
                    sum += s[i] * array1[i];

                }
                int m = sum % 11;
                if (!((m == 2 && s[17] == 'X'||s[17]=='x') || (m != 2 && s[17] == array2[m])))
                    Console.WriteLine("校验位不合法");
                else Console.WriteLine("身份证号合法");
            }
            else
            {
                Console.WriteLine("不匹配");
            }
        }
        //判断日期是否合法
        static bool isLeagal(int year, int month, int day)
        {
            if (year > 2022 || month > 12 || day > 31) return false;
            if (isR(year))
            {
                if ((month == 2 && day > 29)
                    //||(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12&&day>31)
                    || (month == 4 || month == 6 || month == 9 || month == 11 && day > 30)) return false;
            }
            else
            {
                if ((month == 2 && day > 28)
                    || (month == 4 || month == 6 || month == 9 || month == 11 && day > 30)) return false;
            }
            return true;
        }
        //判断是否是闰年
        static bool isR(int year)
        {
            if (year % 4 != 0) return false;
            else if (year % 100 != 0) return false;
            return true;
        }
    }
}
